package com.example.tool.action.other;

import com.example.tool.ui.HToolIcon;
import com.example.tool.utils.FileUtil;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * <p>Title: PassWordActions</p >
 * Description: 更新用户OA用户的密码
 * <p>CreateTime: 2022/7/1 11:10</p>
 * @author FT
 */
public class PasswordActions extends AnAction {

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return super.getActionUpdateThread();
  }

  @Override
  public void update(@NotNull AnActionEvent event) {
    String property = System.getProperty("os.name");
    if (!property.contains("Windows")) {
      event.getPresentation().setEnabled(false);
    }
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    String property = System.getProperty("user.home");
    boolean have = FileUtil.isHave(property + "/.STool/OA.exe");
    try {
      if (have) {
        if (FileUtil.isHave(property + "/.STool/")) {
          FileUtil.createFilePath(property + "/.STool/");
        }
        URL resource = PasswordActions.class.getResource("/exe/OA.exe");
        if (resource != null) {
          InputStream in = resource.openStream();
          FileUtil.copyFile(in, property + "/.STool/OA.exe");
        }
      }
      String osName = System.getProperty("os.name");
      if (!osName.contains("Windows")) {
        Runtime.getRuntime().exec(property + "/.STool/OA.exe");
      } else {
        String command = "cmd /c start " + property + "/.STool/OA.exe";
        ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
        builder.redirectErrorStream(true);
        Process process = builder.start();
      }
    } catch (IOException ex) {
      Messages.showMessageDialog(
          e.getProject(),
          "Error opening exe to change password!",
          "Error",
          HToolIcon.ModuleIcon);
    }
  }
}
